<template>
  <div id="app">
    <h1>待办事项</h1>
    <label for="togAll"><input type="checkbox" id="togAll" @change="toggleAll" :checked="toggleAllStat">标记全部</label>
    <p class="info">
      {{todos.filter(item=>!item.done).length}} / {{todos.length}} 剩余 [<a @click="archive">归档</a>]</p>
      <input type="text" v-model="todoText" @keydown.enter="addTodo" placeholder="今天要做..." title="按回车新建任务">&nbsp;
    <p class="empty" v-if="todos.length == 0">什么都没有...</p>
    <ul class="todos">
      <li v-for="(item,index) in todos" :key="(item, index)">
        <input type="checkbox" v-model="item.done">&nbsp;
        <span :class="{done: item.done}">{{item.title}}</span>
        <button class="delete" @click="removeTodo(index)">删除</button>
      </li>
    </ul>
    <footer>2019 &copy; Powered by <a href="https://cn.vuejs.org" target="__blank">Vue.js</a>, written by <a href="https://github.com/rickweishaw" target="__blank">RCWei</a></footer>
  </div>
</template>

<script>
let todos = [];
export default {
  name: 'app',
  data() { return {
      todos,
      todoText: '',
      curEdit: null
    }
  }, methods: {
    addTodo () {
      let todoText = this.todoText.trim();
      if (!todoText.length) { return }
      let todos = this.todos;
      this.todos.push({
        id: todos.length ? todos[todos.length-1].id+1 : 1,
        title: todoText,
        done: false
      })
      this.todoText = '';
    },
    removeTodo (index) { this.todos.splice(index, 1) },
    archive () {
      if (this.todos.length == 0) {
        alert('没有任务归档');
      } else {
        for (let i = 0; i < this.todos.length; i++) {
          if (this.todos[i].done) {
            this.todos.splice(i, 1);
            i--;
          }
        }
      }
      
    },
    toggleAll(e) {
      let checked = e.target.checked;
      this.todos.length == 0 ? alert('没有任务标记'):this.todos.forEach(item=> {item.done = checked});
    }
  }, computed: {
    countLeft: {get() {return todos.filter(item=>!item.done).length;}},
    toggleAllStat: {get() {return this.todos.every(t=>t.done)}}
  }
}
</script>
